import os
import time
from django.forms.models import model_to_dict
from flask import session
from website_server.models import ArticleTab, CollectTab, IslikeTab,UserinfoTab
from website_server.utils import getTime,getID, http_post,log_in,model_to_list
from django.http import HttpResponse,JsonResponse

# Create your views here.
# 上传文章
@log_in
def uploadArticle(request):
  try:
    rq = request.POST
    articleid = getID()
    path = 'static/article/' + articleid + '.html'
    articleTab = ArticleTab()
    articleTab.articleid = articleid
    articleTab.username = UserinfoTab.objects.get(username=request.session['user'])
    articleTab.time = getTime()
    articleTab.title = rq.get('title')
    articleTab.detail = '/' + path
    articleTab.state = '待审核'
    articleTab.tag = rq.get('tag')
    articleTab.istop = 0
    articleTab.visit = 0
    with open(path, 'w', encoding="utf-8") as f:
      f.write(rq['detail'])
    articleTab.save()
    return HttpResponse(1)
  except Exception as err:
    return HttpResponse(err)

# 获取用户文章
@http_post
def getUserArticle(request):
  try:
    rq = request.POST
    username = rq.get('userName',False) or request.session.get('user')
    article = ArticleTab.objects.filter(username=username).order_by('-time')
    return JsonResponse({'data': model_to_list(article)})
  except Exception:
    return HttpResponse(0)

# 删除文章
@log_in
def removeArticle(request):
  try:
    rq = request.POST
    id = rq.get('id')
    article = ArticleTab.objects.get(articleid=id)
    article.delete()
    path = 'static/article/' + id + '.html'
    if os.path.isfile(path):
      os.remove(path)
    return HttpResponse(1)
  except Exception:
    return HttpResponse('系统异常')

# 修改文章
@log_in
def changeArticle(request):
  rq = request.POST
  try: 
    if rq.get('id'):
      articleid = rq.get('id')
      path = 'static/article/' + articleid + '.html'
      with open(path, 'w', encoding="utf-8") as f:
        f.write(rq.get('detail'))
      article = ArticleTab.objects.get(articleid=rq.get('id'))
      article.state = '待审核'
      article.title = rq.get('title')
      article.tag = rq.get('tag')
      article.time = getTime()
      article.visit = 0
      article.save()
      return HttpResponse(1)
    else:
      return HttpResponse('参数错误')
  except:
    return HttpResponse('文章不存在!')

# 获取全部文章数据
@http_post
def getAllArticle(request):
  article = ArticleTab.objects.filter(state='已通过').order_by('-istop','-time')
  result = [{
    **model_to_dict(x.username),
    **model_to_dict(x),
    'likeCount': IslikeTab.objects.filter(articleid=x.articleid).count()
  } for x in article]
  return JsonResponse({'data': result})

# 获取单个文章数据
@http_post
def getArticle(request):
  rq = request.POST
  try:
    if rq.get('id') != None:
      Article = ArticleTab.objects.filter(articleid=rq.get('id')).first()
      if model_to_dict(Article).get('username') != request.session.get('user'):
        visitTime = request.session.get('visitTime')
        if visitTime == None or int(time.time()) - visitTime > 3:
          Article.visit += 1
          Article.save()
          request.session['visitTime'] = int(time.time())
          request.session.set_expiry(0)
      if model_to_dict(Article).get('state') != '已通过':
        return HttpResponse('文章' + model_to_dict(Article).get('state'))
      result = {
        **model_to_dict(Article),
        'like': 1 if IslikeTab.objects.filter(username=request.session.get('user'),articleid=rq.get('id')).first() else 0,
        'collect': 1 if CollectTab.objects.filter(username=request.session.get('user'),articleid=rq.get('id')).filter() else 0,
        'collectCount': CollectTab.objects.filter(articleid=rq.get('id')).count()
      }
      userArticle = ArticleTab.objects.all()
      return JsonResponse({'result': result, 'article': model_to_list(userArticle)})
    else: 
      return HttpResponse('参数错误')
  except Exception as err:
    print(err)
    return HttpResponse(err)

# 点赞文章
@log_in
def isLike(request):
  rq = request.POST
  username = request.session.get('user',None)
  id = rq.get("id")
  if username != None and id != None:
    isLike = IslikeTab.objects.filter(username=username,articleid=id).first()
    if isLike:
      isLike.delete()
      return HttpResponse(0)
    else:
      isLike = IslikeTab.objects.create(
        username=UserinfoTab.objects.get(username=username),
        articleid=ArticleTab.objects.get(articleid=id),
        islike=1)
      return HttpResponse(1)
  else:
    return HttpResponse('参数错误')

# 收藏文章
@log_in
def isCollect(request):
  rq = request.POST
  id = rq.get('id')
  username = request.session.get('user')
  if id != None and username != None:
    isCollect = CollectTab.objects.filter(username=username,articleid=id)
    if isCollect:
      isCollect.delete()
      return HttpResponse(0)
    else:
      isCollect = CollectTab.objects.create(
        username=UserinfoTab.objects.get(username=username),
        articleid=ArticleTab.objects.get(articleid=id),
        collect=True
      )
      return HttpResponse(1)
  else:
    return HttpResponse('参数错误!')

# 获取用户收藏文章
@log_in
def getUserCollect(request):
  username = request.session.get('user')
  if username:
    collect = CollectTab.objects.filter(username=username)
    result = [{
      **model_to_dict(x.articleid)
    } for x in collect]
    return JsonResponse({'data':result})
  else:
    return HttpResponse('登陆已过期')